package com.xhtranslate.service.baidu.serviceImpl;

import com.baidu.aip.ocr.AipOcr;
import com.xhtranslate.common.config.TranslateConfig;
import com.xhtranslate.common.util.FileUtil;
import com.xhtranslate.common.util.AddUseLimitThreadUtil;
import com.xhtranslate.service.baidu.service.BaiduOcrService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author liuxuhuang
 * @version 1.0
 * @package com.xhtranslate.service.baidu.serviceImpl
 * @date 2022/11/11 16:25:35
 * @description
 */
@Service
@Slf4j
public class BaiduOcrServiceImpl implements BaiduOcrService {
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private AipOcr aipOcrClient;
    @Autowired
    private AddUseLimitThreadUtil addUseLimitThreadUtil;

    @Override
    public String ocrImg(MultipartFile file) throws IOException {
        File file2 = fileUtil.saveImg(file);
        String absolutePath = file2.getAbsolutePath();
        JSONObject jsonObject = aipOcrClient.basicAccurateGeneral(absolutePath, null);
        JSONArray wordsResult = jsonObject.getJSONArray("words_result");
        StringBuffer stringBuffer = new StringBuffer();
        System.out.println(wordsResult);
        for (int i = 0; i < wordsResult.length(); i++) {
            String words = wordsResult.getJSONObject(i).getString("words");
            stringBuffer.append(words).append("\n");
        }
        addUseLimitThreadUtil.addCreditLimit(TranslateConfig.BaiduOcrRedisName, 1);
        String string = stringBuffer.toString();
        log.info("百度ocr识别结果");
        log.info(string);
        return string;
    }
}
